<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="username" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model.number="userAge" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="sex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="addFn">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr v-show="arr.length !== 0">
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in arr" :key="item.id">
          <td>{{ index + 1 }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.sex }}</td>
          <td>
            <button @click="delFn(item.id)">删除</button>
            <button @click="editFn(item.id)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      flag: "", //用于区分添加还是修改
      username: "",
      userAge: 0,
      sex: "",
      arr: [
        {
          id: 1,
          name: "Tom",
          age: 19,
          sex: "男",
        },
        { id: 2, name: "Jone", age: 21, sex: "女" },
      ],
    };
  },
  methods: {
    addFn() {
      //添加
      if (this.flag === "") {
        if (
          this.username.trim().length === 0 ||
          this.userAge === 0 ||
          this.sex.length === 0
        ) {
          return alert("内容不能为空");
        }
        this.arr.push({
          id: +new Date(),
          name: this.username,
          age: this.userAge,
          sex: this.sex,
        });
      } else {
        // 修改
        this.flag.name = this.username;
        this.flag.age = this.userAge;
        this.flag.sex = this.sex;
      }
      // 清空
      this.username = "";
      this.userAge = 0;
      this.sex = "";
      // 重置flag的值
      this.flag = "";
    },
    // 删除
    delFn(id) {
      this.arr = this.arr.filter((item) => item.id !== id);
    },

    // 编辑
    editFn(id) {
      // 回显数据 根据id去 查找find到arr对应的的id数据
      // find 查找到符合条件的那一项
      const obj = this.arr.find((item) => item.id === id);
      console.log(obj);
      this.flag = obj;
      // 修改数据
      this.username = obj.name;
      this.userAge = obj.age;
      this.sex = obj.sex;
    },
  },
};
</script>
